package com.guxingke.gsb.repo;

import com.guxingke.gsb.model.IParseable;
import com.guxingke.gsb.model.IndexModel;
import com.guxingke.gsb.model.Page;
import com.guxingke.gsb.model.Post;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by 孤星可 on 2015/11/26.
 *
 * @author guxingke
 * @since 2015/11/26
 */
public class GsbRepo {
    private static final List<Post> posts = new ArrayList<>();

    private static final List<Page> pages = new ArrayList<>();

    private static final List<IParseable> others = new ArrayList<>();

    private static GsbRepo ourInstance = new GsbRepo();

    public static GsbRepo getInstance() {
        return ourInstance;
    }

    private GsbRepo() {
    }

    public static void addParseable(IParseable parseable) {
        String layout = parseable.getLayout();
        if ("post".equals(layout)) {
            posts.add((Post) parseable);
        } else if ("page".equals(layout)) {
            pages.add((Page) parseable);
        } else {
            others.add(parseable);
        }
    }

    public static List<IParseable> getOthers() {
        return Collections.unmodifiableList(others);
    }

    public static List<Page> getPages() {
        return Collections.unmodifiableList(pages);
    }

    /**
     * 返回不可变的以date排序的posts list
     *
     * @return list
     */
    public static List<Post> getPosts() {
        Collections.sort(posts, (x, y) -> {
            return x.getDate().before(y.getDate()) ? 1 : -1;
        });
        return Collections.unmodifiableList(posts);
    }

    public static List<IndexModel> getIndexs(int pageSize) {
        List<IndexModel> results = new ArrayList<>();
        int size = getPosts().size();
        int page = size / pageSize + 1;
        for (int i = 1; i < page + 1; i++) {
            IndexModel index = getIndex(i, pageSize);
            if (null == index) {
                continue;
            }
            results.add(index);
        }
        return results;
    }

    private static IndexModel getIndex(int page, int pageSize) {
        List<Post> posts = getPosts();
        int size = posts.size();
        int start = pageSize * (page - 1);
        boolean hasMore = (start + pageSize) < size;
        int end = hasMore ? start + pageSize : size;
        List<Post> subList = posts.subList(start, end);
        return new IndexModel(new ArrayList<>(subList), page, hasMore);
    }
}
